﻿using System;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    public class EditToggle
    {
        Toggle toggle;
        string storageKey;
        bool currValue, oldValue;

        public static void Create(Toggle toggle, string key, bool defaultValue, Action<bool> onToggleEdit)
        {
            new EditToggle(toggle, key, defaultValue, onToggleEdit);
        }

        private EditToggle(Toggle toggle, string key, bool defaultValue, Action<bool> onToggleEdit)
        {
            this.toggle = toggle;
            this.storageKey = key;
            this.currValue = DataStorage.GetInt(storageKey, defaultValue ? 1 : 0) == 1;
            this.toggle.isOn = this.currValue;
            this.toggle.onValueChanged.RemoveAllListeners();
            this.toggle.onValueChanged.AddListener((bool v) =>
            {
                if (onToggleEdit != null) onToggleEdit(v);
                this.currValue = v;
                //焦点移开确保改变生效
                EventSystem.current.SetSelectedGameObject(toggle.transform.parent.gameObject);
            });
            if (onToggleEdit != null) onToggleEdit(this.currValue);
            MainController.onEditModeEnable += (bool b, bool save) =>
            {
                if (b)
                {
                    this.currValue = DataStorage.GetInt(storageKey, defaultValue ? 1 : 0) == 1;
                    toggle.isOn = this.currValue;
                    this.oldValue = this.currValue;
                }
                else
                {
                    if (save)
                    {
                        DataStorage.SetInt(storageKey, this.currValue ? 1 : 0);
                    }
                    else
                    {
                        toggle.isOn = this.oldValue;
                    }
                }
            };
        }

    }
}